package com.naizhuai.ui.user.simulation;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.apistore.UserManageDataApiStore;
import com.naizhuai.network.exception.ValidateException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.components.swipeback.SwipeBackActivity;
import com.naizhuai.ui.entity.User.DeviceData;
import com.naizhuai.ui.entity.User.Simulation;
import com.naizhuai.ui.entity.User.SimulationData;
import com.naizhuai.ui.user.UserManageDataApiStoreIml;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscription;

public class SimulationSettingActivity extends SwipeBackActivity implements DeviceDataAdapter.AddAndDeleteCallBack {
    @BindView(R.id.btn_edit)
    TextView btnEdit;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.device_container)
    LinearLayout deviceContainer;
    @BindView(R.id.device_arrow)
    ImageView deviceArrow;
    @BindView(R.id.device_list)
    RecyclerView deviceList;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
   private Subscription mSubscription;

    private List<Simulation> simulationList;
    private List<DeviceData> mDeviceDataList;

    public static void start(Context context) {
        Intent intent = new Intent(context, SimulationSettingActivity.class);
        if (context instanceof BaseActivity)
            ((BaseActivity) context).startActivityTransition(intent);
    }

    @BindView(R.id.data_describe_list)
    RecyclerView dataDescribeList;
    WriteDataAdapter mWriteDataAdapter;
    DeviceDataAdapter mDeviceDataAdapter;
    private UserManageDataApiStore mUserManageDataApiStore;
    private int mHiddenViewMeasuredHeight;
    private int addHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        dataDescribeList.setNestedScrollingEnabled(false);
        dataDescribeList.setLayoutManager(new LinearLayoutManager(this));
        dataDescribeList.setAdapter(mWriteDataAdapter = new WriteDataAdapter());

        deviceList.setLayoutManager(new LinearLayoutManager(this));
        deviceList.setAdapter(mDeviceDataAdapter = new DeviceDataAdapter(this));
        initData();
        toolbar.setNavigationOnClickListener(v -> finish());
//        mHiddenLayout.post(new Runnable() {
//            @Override
//            public void run() {
//                mHiddenViewMeasuredHeight=mHiddenLayout.getHeight();
//                mHiddenLayout.setVisibility(View.GONE);
//            }
//        });


    }

    private boolean open_state = false;

    private void initData() {
        if (mUserManageDataApiStore == null) {
            mUserManageDataApiStore = UserManageDataApiStoreIml.getInstance();
        }

        showWaitDiaLog();
        mUserManageDataApiStore.getComPanySimalationData()
                .subscribe(new NetWorkObserver<SimulationData>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(errormsg);
                    }
                    @Override
                    protected void onSuccess(SimulationData result) {
                        hideWaitDialog();
                        mWriteDataAdapter.setEditenable(false);
                        mWriteDataAdapter.setSimulation(result.normalList);
                        mDeviceDataAdapter.setEditenable(false);
                        mDeviceDataAdapter.setResult(result.tmdList);
                        simulationList = result.normalList;
                        mDeviceDataList = result.tmdList;
                        deviceList.post(new Runnable() {
                            @Override
                            public void run() {
                                mHiddenViewMeasuredHeight = deviceList.getHeight();
                                addHeight = mHiddenViewMeasuredHeight / (mDeviceDataList.size()+1);
                                addHeight+=10;
                                deviceList.setVisibility(View.GONE);
                            }
                        });
                    }
                });
        UserManageDataApiStoreIml.getInstance()
                .getuserinfo()
                .subscribe(new NetWorkObserver<PersonUserBean>() {
                    @Override
                    public void onFail(String errormsg) {
                         shortToast(errormsg);
                    }
                    @Override
                    public void onSuccess(PersonUserBean result) {
                        String companyPowerCode = result.getCompanyPowerCode();
                        if (!companyPowerCode.equals(ConstantsState.COM_TARGET_MANAGER_LEVEL)) {
                            btnEdit.setVisibility(View.GONE);
                            btnSubmit.setVisibility(View.GONE);
                        }
                    }
                });
        deviceContainer.setOnClickListener(v -> {
            changImgState();
            changeAnim();
        });
    }

    private void changeAnim() {
        if (deviceList.getVisibility() == View.GONE) {
            animateOpen(deviceList);
        } else {
            animateClose(deviceList);
        }
    }

    private void changImgState() {
        open_state = !open_state;
        if (open_state) {
            deviceArrow.setRotation(-90);
        } else {
            deviceArrow.setRotation(90);
        }
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_simulation_setting;
    }

    @OnClick(R.id.btn_edit)
    public void onBtnEditClicked() {
        DialogUtils.showSureDialog(getActivityContext(), getString(R.string.simulation_hint), v -> {
            btnEdit.setVisibility(View.GONE);
            btnSubmit.setVisibility(View.VISIBLE);
            mWriteDataAdapter.setEditenable(true);
            mWriteDataAdapter.setSimulation(simulationList);
            mDeviceDataAdapter.setEditenable(true);
            mDeviceDataAdapter.setResult(mDeviceDataList);
        });

    }


    @OnClick(R.id.btn_submit)
    public void onBtnSubmitClicked() {
        try {
            List<Simulation> simulations = mWriteDataAdapter.getSimulation();
            List<DeviceData> deviceData = mDeviceDataAdapter.getResult();
            ArrayList<Simulation> temp=new ArrayList<>(simulations);
            for (int i = 0; i < deviceData.size(); i++) {
                int tempnum=i+1;
                DeviceData data = deviceData.get(i);
                temp.add(new Simulation("sbzj_" + tempnum, "", data.sbzj, tempnum+"", data.machineName));
                temp.add(new Simulation("sbhd_" + tempnum, "", data.sbhd, tempnum+"", data.machineName));
            }
            String simulationData = new Gson().toJson(temp);
            showWaitDiaLog();
            mSubscription= mUserManageDataApiStore.setComPanySimalationData(simulationData)
                    .subscribe(new NetWorkObserver<String>() {
                        @Override
                        protected void onFail(String errormsg) {
                            hideWaitDialog();
                            shortToast(errormsg);
                        }

                        @Override
                        protected void onSuccess(String result) {
                            hideWaitDialog();
                            if (ConstantsState.isResultOk(result)) {
                                shortToast(getString(R.string.action_ok));
//                                btnEdit.setVisibility(View.VISIBLE);
//                                btnSubmit.setVisibility(View.GONE);
                                finish();
                            } else {
                                shortToast(getString(R.string.action_fail));
                            }
                        }
                    });
        } catch (ValidateException expection) {
            shortToast(expection.getMessage());
        }
    }

    private void animateOpen(View v) {
        v.setVisibility(View.VISIBLE);
        ValueAnimator animator = createDropAnimator(v, 0,
                mHiddenViewMeasuredHeight);
        animator.start();
    }

    private void animateClose(final View view) {
        int origHeight = view.getHeight();
        ValueAnimator animator = createDropAnimator(view, origHeight, 0);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                view.setVisibility(View.GONE);
            }

        });
        animator.start();
    }

    private ValueAnimator createDropAnimator(final View v, int start, int end) {
        ValueAnimator animator = ValueAnimator.ofInt(start, end);
        animator.addUpdateListener(arg0 -> {
            int value = (int) arg0.getAnimatedValue();
            ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
            layoutParams.height = value;
            v.setLayoutParams(layoutParams);

        });
        return animator;
    }

    @Override
    public void add() {
        mDeviceDataAdapter.add();
        ValueAnimator animator = createDropAnimator(deviceList, mHiddenViewMeasuredHeight,
                mHiddenViewMeasuredHeight + addHeight);
        animator.start();
        mHiddenViewMeasuredHeight = mHiddenViewMeasuredHeight + addHeight;
    }

    @Override
    public void delete(int position) {
        mDeviceDataAdapter.delete(position);
        ValueAnimator animator = createDropAnimator(deviceList, mHiddenViewMeasuredHeight,
                mHiddenViewMeasuredHeight - addHeight);
        animator.start();
        mHiddenViewMeasuredHeight = mHiddenViewMeasuredHeight - addHeight;
    }

    @Override
    public void onBackPressed() {
        if (isWaitDialogShowing1()) {
            if (mSubscription!=null){
                 if (mSubscription.isUnsubscribed()){
                     mSubscription.unsubscribe();
                 }
            }
            hideWaitDialog();
        } else {
            super.onBackPressed();
        }
    }
}
